#pragma once

#include <iostream>
#include <string>
#include "log.hpp"
#include "Init.hpp"

Init init;

extern Log log;

class Task{
public:
    Task(const int sockfd, const std::string ip, const uint16_t port)
        : _sockfd(sockfd), _ip(ip), _port(port)
    {}

    void Run(){
        char buffer[4096];
        while(true){
            ssize_t n = read(_sockfd, buffer, sizeof(buffer));
            if (n > 0){
                buffer[n] = 0;
                // 信息处理
                std::cout << "server get a message: " << buffer << std::endl;
                // std::string echo_string = "tcpserver echo# ";
                // echo_string += buffer;

                std::string echo_string = init.translation(buffer);

                // 信息发送
                ssize_t s = write(_sockfd, echo_string.c_str(), echo_string.size());
                // 修改点1：对写入做异常处理
                if(s < 0){
                    log(Warning, "write error, errno: %d, strerror: %s", errno, strerror(errno));
                }
            }
            else if (n == 0){
                log(INFO, "%s:%d quit, server close sockfd: %d", _ip.c_str(), _port, _sockfd);
                break;
            }
            else{
                log(Warning, "read error, sockfd: %d, clientip: %s, clientport: %d", _sockfd, _ip.c_str(), _port);
                break;
            }
        }
    }

    ~Task()
    {}
private:
    int _sockfd;
    std::string _ip;
    uint16_t _port;
};